/**
 * 开单页中显示验光信息模块内容
 */
import { addEyeDoctor, deleteEyeDoctor, getEyeDoctorList } from '@/services/order/api';
import { isNull, showMsg } from '@/utils/utils';
import { DeleteTwoTone, PlusOutlined } from '@ant-design/icons';
import ProForm, { ProFormCheckbox, ProFormDependency, ProFormRadio, ProFormSelect, ProFormSwitch, ProFormText } from '@ant-design/pro-form';
import { Checkbox, Col, Divider, Form, FormInstance, Input, Row, Select } from 'antd';
import React, { ReactElement, forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import './style.less';
import { isShowEyeInfo, isShowFrameInfo } from './Detail';

interface EyeInfoProps {
  orderObj: any;
}

const SettlementInfo: React.FC<EyeInfoProps> = forwardRef((props, ref) => {
  const { orderObj = {} } = props;
  const formRef = useRef<FormInstance>();

  const [doctorName, setDoctorName] = useState<string>('');
  const [doctorListY, setDoctorListY] = useState([]);
  const [doctorListD, setDoctorListD] = useState([]);
  const [BYO, setBYO] = useState<boolean>(false);

  useEffect(() => {
    if (orderObj.frame_flag == '1' || orderObj.frame_flag == '2') {
      setBYO(true);
      orderObj.frame_flag = 1;
    }
    getEyeDoctorList().then(res => {
      setDoctorListData(res);
      setTimeout(() => {
        formRef.current?.setFieldsValue({
          optician_id: { value: orderObj.optician_id, label: orderObj.optician_name },
          doctor_id: { value: orderObj.doctor_id, label: orderObj.doctor_name }
        });
      }, 100);
    });
  }, [orderObj]);

  const setDoctorListData = (res: any) => {
    const doctorListY: any = [], doctorListD: any = [];
    res?.record_list?.forEach(({ doctor_id, doctor_name, doctor_type }: any) => {
      if (doctor_type === 'Y') {
        doctorListY.push({ value: doctor_id, label: doctor_name });
      } else if (doctor_type === 'D') {
        doctorListD.push({ value: doctor_id, label: doctor_name });
      }
    });
    setDoctorListY(doctorListY);
    setDoctorListD(doctorListD);
  };

  // 暴露的子组件方法，给父组件调用
  useImperativeHandle(ref, () => ({
    getFields: () => {
      const fieldsValue = formRef.current?.getFieldsValue();
      return {
        ...fieldsValue,
        is_slip: fieldsValue.is_slip === true ? 'Y' : 'N',
        frame_flag: fieldsValue.frame_flag ?? 0,
        doctor_id: fieldsValue.doctor_id?.value,
        doctor_name: fieldsValue.doctor_id?.label,
        optician_id: fieldsValue.optician_id?.value,
        optician_name: fieldsValue.optician_id?.label
      };
    },
    reload: () => {
      formRef?.current?.resetFields();
    }
  }))

  // 格式化球镜柱镜数据
  const formatterData = (value: any) => {
    return isNull(value) ? '' : parseFloat(value) >= 0 ? `+${parseFloat(value).toFixed(2)}` : parseFloat(value).toFixed(2)
  }

  // console.log('formRef.current', formRef.current)

  const addDoctor = async (type: 'Y' | 'D') => {
    if ((doctorName ?? '').trim() === '') {
      showMsg(`请输入${type === 'Y' ? '验光师' : '就诊医生'}名字`);
      return;
    }
    try {
      const addRes = await addEyeDoctor(doctorName as string, type);
      const res = await getEyeDoctorList();
      setDoctorListData(res);
      await new Promise(resolve => setTimeout(resolve, 50));
      const labelInValueData = { value: addRes?.doctor_id, label: addRes?.doctor_name };
      formRef.current?.setFieldsValue(type === 'Y' ? { optician_id: labelInValueData } : { doctor_id: labelInValueData });
    } catch (err: any) {
      showMsg(err?.data?.errmsg);
    }
  };

  const doctorOptionRender = ({ value, label }: { value: string, label: string }, type: 'Y' | 'D') => {
    return <div style={{ position: "relative" }}>
      <span>{label}</span><DeleteTwoTone twoToneColor='red' style={{ position: "absolute", right: 0, top: 3, fontSize: 16 }} onClick={async e => {
        try {
          await deleteEyeDoctor(value);
          formRef.current?.setFieldsValue(type === 'Y' ? { optician_id: undefined } : { doctor_id: undefined });
          const res = await getEyeDoctorList();
          setDoctorListData(res);
        } catch (err: any) {
          showMsg(err?.data?.errmsg);
        }
        e.stopPropagation();
      }} />
    </div>;
  };

  const customDropdown = (menu: ReactElement, text: string, type: 'Y' | 'D') => {
    return (
      <div>
        {menu}
        <Divider style={{ margin: '4px 0' }} />
        <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'nowrap', padding: 8 }}>
          <Input style={{ flex: 'auto', height: 24 }} value={doctorName} onChange={e => setDoctorName(e.target.value)} />
          <a style={{ flex: 'none', padding: '8px', display: 'block', cursor: 'pointer' }} onClick={() => addDoctor(type)}>
            <PlusOutlined /> {text}
          </a>
        </div>
      </div>
    );
  };

  return (
    <ProForm
      formRef={formRef}
      className="service-record eyeinfo"
      layout="horizontal"
      submitter={false}
      initialValues={{
        ...orderObj,
        left_degrees: formatterData(orderObj.left_degrees),
        right_degrees: formatterData(orderObj.right_degrees),
        left_astig: formatterData(orderObj.left_astig),
        right_astig: formatterData(orderObj.right_astig),
        isShow: isShowEyeInfo(orderObj),
        frameIsShow: isShowFrameInfo(orderObj),
        is_slip: orderObj.is_slip === 'Y',
        frame_flag: parseInt(orderObj.frame_flag ?? 0) || 1,
        muse: 'H'
      }}
    >
      <div className="header">
        <div className="title">3.配镜信息</div>
        <ProFormSwitch name="isShow" />
      </div>
      <Divider style={{ margin: '10px 0' }} />

      <ProFormDependency name={['isShow']}>
        {({ isShow }) => {
          if (!isShow) {
            return null;
          }
          return (
            <>
              <Row gutter={12}>
                <Col style={{ paddingTop: 5 }}>
                  <h4 style={{ width: 40 }}>用途</h4>
                </Col>
                <Col flex='1'>
                  <ProFormRadio.Group labelCol={{ flex: '0 0 62px' }} label=" " colon={false} name="muse"
                    fieldProps={{ defaultValue: 'H' }} options={museOptions} />
                </Col>
              </Row>
              <Row gutter={12}>
                <Col style={{ paddingTop: 5 }}>
                  <h4 style={{ width: 40 }}>右眼R</h4>
                </Col>
                <Col flex={'0 0 15.8%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label="球镜" name="right_degrees" />
                </Col>
                <Col flex={'0 0 15.8%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label="柱镜" name="right_astig" />
                </Col>
                <Col flex={'0 0 15.8%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label="轴位" name="right_axial" />
                </Col>
                <Col flex={'0 0 15.8%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label="矫正前" name="right_rectify_bef" />
                </Col>
                <Col flex={'0 0 15.8%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label="矫正后" name="right_rectify_af" />
                </Col>
                <Col flex={'0 0 15.8%'}>
                  <ProFormSelect labelCol={{ flex: '0 0 62px' }} label="离焦量" name="right_defocus"
                    fieldProps={{ size: 'small', style: { width: '100%' } }} options={defocusOptions} />
                </Col>
              </Row>
              <Row gutter={12}>
                <Col style={{ marginTop: 5 }}>
                  <h4 style={{ width: 40 }}>左眼L</h4>
                </Col>
                <Col flex={'0 0 15.8%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label="球镜" name="left_degrees" />
                </Col>
                <Col flex={'0 0 15.8%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label="柱镜" name="left_astig" />
                </Col>
                <Col flex={'0 0 15.8%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label="轴位" name="left_axial" />
                </Col>
                <Col flex={'0 0 15.8%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label="矫正前" name="left_rectify_bef" />
                </Col>
                <Col flex={'0 0 15.8%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label="矫正后" name="left_rectify_af" />
                </Col>
                <Col flex={'0 0 15.8%'}>
                  <ProFormSelect labelCol={{ flex: '0 0 62px' }} label="离焦量" name="left_defocus"
                    fieldProps={{ size: 'small', style: { width: '100%' } }} options={defocusOptions} />
                </Col>
              </Row>
              <Row gutter={12}>
                <Col style={{ marginTop: 5 }}>
                  <h4 style={{ width: 40 }}>瞳距</h4>
                </Col>
                <Col flex={'0 0 15.8%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label="总瞳距" name="pup_distance" />
                </Col>
                <Col flex={'0 0 15.8%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label="瞳距右" name="pup_distance_right" />
                </Col>
                <Col flex={'0 0 15.8%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label="瞳距左" name="pup_distance_left" />
                </Col>
              </Row>
              <Row gutter={12}>
                <Col style={{ marginTop: 5 }}>
                  <h4 style={{ width: 40 }}>瞳高</h4>
                </Col>
                <Col flex={'0 0 15.8%'}></Col>
                <Col flex={'0 0 15.8%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label="瞳高右" name="pup_high_right" />
                </Col>
                <Col flex={'0 0 15.8%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label="瞳高左" name="pup_high_left" />
                </Col>
              </Row>
              <Row gutter={12}>
                <Col style={{ flex: '0 0 52px' }}></Col>
                <Col flex={'0 0 31.6%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label="ADD" name="madd" />
                </Col>
                <Col flex={'0 0 63.2%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label={<span style={{ color: 'red' }}>特殊备注</span>} name="special_case" />
                </Col>
              </Row>
              <Row gutter={12}>
                <Col flex={'0 0 52px'}></Col>
                <Col flex={'0 0 31.6%'}>
                  <ProFormText labelCol={{ flex: '0 0 62px' }} label="验光号" name="sight_no" />
                </Col>
                <Col flex={'0 0 31.6%'}>
                  <ProFormSelect
                    label="就诊医生"
                    name="doctor_id"
                    options={doctorListD}
                    labelCol={{ flex: '0 0 62px' }}
                    placeholder="请输入或选择就诊医生"
                    style={{ width: '100%' }}
                    fieldProps={{
                      className: "doctor-select",
                      optionFilterProp: 'children',
                      labelInValue: true,
                      showSearch: true,
                      filterOption: (input, option) => (option?.label as any)?.includes(input),
                      optionItemRender: item => doctorOptionRender(item, 'D'),
                      dropdownRender: menu => customDropdown(menu, '新增就诊医生', 'D'),
                      onDropdownVisibleChange: open => { if (open) setDoctorName(''); }
                    }}
                  />
                </Col>
                <Col flex={'0 0 31.6%'}>
                  <ProFormSelect
                    label="验光师"
                    name="optician_id"
                    options={doctorListY}
                    labelCol={{ flex: '0 0 62px' }}
                    placeholder="请输入或选择验光师"
                    style={{ width: '100%' }}
                    fieldProps={{
                      className: "doctor-select",
                      optionFilterProp: 'children',
                      labelInValue: true,
                      showSearch: true,
                      filterOption: (input, option) => (option?.label as any)?.includes(input),
                      optionItemRender: item => doctorOptionRender(item, 'Y'),
                      dropdownRender: menu => customDropdown(menu, '新增验光师', 'Y'),
                      onDropdownVisibleChange: open => { if (open) setDoctorName(''); }
                    }}
                  />
                </Col>
              </Row>
            </>
          );
        }}
      </ProFormDependency>

      <div className="header">
        <div className="title">4.镜架信息</div>
        <ProFormSwitch name="frameIsShow" />
      </div>
      <Divider style={{ margin: '10px 0' }} />

      <ProFormDependency name={['frameIsShow']}>
        {({ frameIsShow }) => (!frameIsShow ? null : (
          <>
            <Row gutter={12}>
              <Col style={{ paddingTop: 5, width: 52 }} />
              <Col flex={'0 0 23%'}>
                <ProFormText labelCol={{ flex: '0 0 62px' }} label="框宽" name="frame_width" />
              </Col>
              <Col flex={'0 0 23%'}>
                <ProFormText labelCol={{ flex: '0 0 62px' }} label="框高" name="frame_height" />
              </Col>
              <Col flex={'0 0 23%'}>
                <ProFormText labelCol={{ flex: '0 0 62px' }} label="中梁" name="frame_middle" />
              </Col>
              <Col flex={'0 0 23%'}>
                <ProFormText labelCol={{ flex: '0 0 72px' }} label="镜对角直径" name="frame_diagonal" />
              </Col>
            </Row>
            <Row gutter={12}>
              <Col style={{ paddingTop: 5, width: 52 }} />
              <Col flex={'0 0 23%'}>
                <ProFormText labelCol={{ flex: '0 0 62px' }} label="型号" name="frame_model" />
              </Col>
              <Col flex={'0 0 23%'}>
                <ProFormText labelCol={{ flex: '0 0 62px' }} label="框型" name="frame_material" />
              </Col>
              <Col flex={'0 0 23%'}>
                <ProFormCheckbox labelAlign='right' labelCol={{ flex: '0 0 156px' }} label="是否需要防滑套" name="is_slip" />
              </Col>
              <Col flex={'0 0 23%'}>
                <Form.Item label='是否自备镜架'>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                    <Checkbox checked={BYO} onChange={e => { setBYO(e.target.checked); formRef.current?.resetFields(['frame_flag']) }} />
                    {
                      BYO &&
                      <Form.Item noStyle name='frame_flag'>
                        <Select style={{ width: 80 }} size='small' options={[{ label: '留', value: 1 }, { label: '未留', value: 2 }]} />
                      </Form.Item>
                    }
                  </div>
                </Form.Item>
              </Col>
            </Row>
          </>
        ))}
      </ProFormDependency>
    </ProForm>
  );
});
export default SettlementInfo;

export const eyeInfoColumn = [
  'muse',
  'right_degrees', 'right_astig', 'right_axial', 'right_rectify_bef', 'right_rectify_af', 'right_defocus',
  'left_degrees', 'left_astig', 'left_axial', 'left_rectify_bef', 'left_rectify_af', 'left_defocus',
  'pup_distance', 'pup_distance_right', 'pup_distance_left',
  'pup_high_right', 'pup_high_left',
  'madd', 'sight_no', 'optician_id', 'doctor_id', 'special_case'
];

export const frameInfoColumn = [
  'frame_diagonal', 'frame_height', 'frame_middle', 'frame_width', 'frame_material', 'frame_model', 'is_slip', 'frame_flag'
];

export const defocusOptions = [
  {
    label: '高',
    value: '高'
  },
  {
    label: '中',
    value: '中'
  },
  {
    label: '低',
    value: '低'
  }
];

export const museOptions = [
  { label: '远用', value: 'H' },
  { label: '近用', value: 'S' }
];
